package security;

import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import org.springframework.context.support.MessageSourceAccessor;
import org.springframework.security.core.SpringSecurityMessageSource;
import org.springframework.security.core.authority.GrantedAuthorityImpl;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import dao.interf.IAuthorityDAO;
import dao.interf.IUserDAO;
import dao.pojo.Authority;
import dao.pojo.User;

public class MyUserDetailsService implements UserDetailsService {
	protected MessageSourceAccessor messages;
	private String rolePrefix;

	private IUserDAO userDao;
	private IAuthorityDAO authDao;

	public void setUserDao(IUserDAO userDao) {
		this.userDao = userDao;
	}

	public void setAuthDao(IAuthorityDAO authDao) {
		this.authDao = authDao;
	}

	public MyUserDetailsService() {
		messages = SpringSecurityMessageSource.getAccessor();
		rolePrefix = "";
	}

	public UserDetails loadUserByUsername(String username) {
		User user = null;
		try {
			List<User> lstU = userDao.findByProperties(
					new String[] { "userName" }, new Object[] { username });
			if (null != lstU && !lstU.isEmpty())
				user = lstU.get(0);
		} catch (Exception e) {
			e.printStackTrace();
		}
		MyUserDetails udetail = new MyUserDetails();
		if (null == user)
			throw new UsernameNotFoundException(messages.getMessage(
					"JdbcDaoImpl.notFound", new Object[] { username },
					"用户 {0} 不存在"), username);

		udetail.setUserId(user.getUserId());
		udetail.setUsername(username);
		udetail.setPassword(user.getPassword());
		udetail.setAccountNonExpired(true);
		udetail.setAccountNonLocked(true);
		udetail.setCredentialsNonExpired(true);
		udetail.setEnabled(true);
		List<Authority> auths = authDao.getAuthorityByUser(user);
		Set<GrantedAuthorityImpl> dbAuths = new HashSet<GrantedAuthorityImpl>();
		for (Iterator<Authority> ite = auths.iterator(); ite.hasNext();) {
			Authority a = ite.next();
			GrantedAuthorityImpl authority = new GrantedAuthorityImpl(a
					.getAuthority());
			dbAuths.add(authority);
		}
		udetail.setAuthorities(dbAuths);
		return udetail;
	}

	public void setRolePrefix(String rolePrefix) {
		this.rolePrefix = rolePrefix;
	}

	protected String getRolePrefix() {
		return rolePrefix;
	}
}
